
/*
 * 实现：
 * - 外部传入搜索的 spec，本地通过 spec 源进行查找
 */
const fs = require('fs-extra')
const md5 = require('md5-node')
const open = require('open')
const print = require('../../lib/print')

// 官方源+私有源
const specsSourcePath = ['/Users/caoyq/.cocoapods/repos/master/Specs', 
                         '/Users/caoyq/.cocoapods/repos/weimob-ap-wmappspecs_ios', 
                         '/Users/caoyq/.cocoapods/repos/weimob-saasapp-saasapp_ios-xyappspecs_ios']

module.exports = async function (searchSpec) {

    // 通过 md5 值获取前三层的文件夹名称
    let specMd5 = md5(searchSpec)
    let firstLevelFolder = specMd5.substr(0,1)
    let secondLevelFolder = specMd5.substr(1,1)
    let thirdLevelFolder = specMd5.substr(2,1)
    // 搜索的结果
    let specPath = ''

    // for in 内部可以用 await，串行执行
    for (let index in specsSourcePath) {
        let item = specsSourcePath[index];
        // 第一步：先查找自定义的源，直接拼装路径
        let _specPath = `${item}/${searchSpec}/`
        let result = await fs.existsSync(_specPath)
        if (result) {
            specPath = _specPath  
            break
        }

        // 第二步：查找 Cocoapods 源，按照 md5 前 3 位值来排序，获取组合路径
        _specPath = `${item}/${firstLevelFolder}/${secondLevelFolder}/${thirdLevelFolder}/${searchSpec}/`
        result = await fs.existsSync(_specPath)
        if (result) {
            specPath = _specPath  
            break
        }
    }

    // 打开结果
    if (specPath.length > 0) {
        print.successLog(`${searchSpec} 本地路径为：${specPath}`)
        open(specPath)
    } else {
        print.errorLog(`未找到 ${searchSpec}`)
    }
}

